package com.elong.qadev.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
/**
 * 
* @ClassName: AuthFilter
* @Description: TODO(登陆过滤验证)
* @author kangchen
* @date 2015年9月14日
*
 */
public class AuthFilter implements Filter {
	Logger logger = Logger.getLogger(AuthFilter.class);
	@Override
	public void destroy() {
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		logger.debug("验证指定jsp过滤是否存在登陆session");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String requestURI = req.getRequestURI().substring(
				req.getRequestURI().indexOf("/", 1),
				req.getRequestURI().length());

		// 如果第一次请求不为登录、注册页面,则进行检查用session内容,如果为登录页面就不去检查.
		if (!("/login.jsp".equals(requestURI))
				&& !("/user/new_account.jsp".equals(requestURI))&&!("/user/pwdUpdate.jsp").equals(requestURI)) {
			// 我们用false表示没有取得到session则设置为session为空.
			HttpSession session = req.getSession(false);
			// 如果session中没有任何东西.
			if (session == null || session.getAttribute("user") == null) {
				res.sendRedirect(req.getContextPath() + "/login.jsp");
				return;
			}
			logger.debug("获取session成功，转发登陆请求");

		}
		chain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
}
